import router from "./index";
import store from "../store/index";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import getPageTitle from "@/utils/pageTitle";
import { progressBar, routesWhiteList } from "../config/settings";
import { getToken, removeToken, removeUserName } from "@/utils/app";

// 简单配置 NProgress
NProgress.configure({
  easing: "ease",
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false
});

router.beforeEach((to, from, next) => {
  if (progressBar) NProgress.start();
  if (getToken()) {
    if (to.path === "/login") {
      removeToken();
      removeUserName();
      store.commit("app/SET_TOKEN", "");
      store.commit("app/SET_USERNAME", "");
      if (progressBar) NProgress.done();
      next();
    } else {
      if (store.getters["app/roles"].length === 0) {
        store.dispatch("permission/getRoles").then(res => {
          let role = res;
          let btnPerm = res.btnPerm;
          store.commit("app/SET_ROLES", role);
          // store.commit("app/SET_BUTTON", btnPerm);
          store.dispatch("permission/creatRouter", res).then(response => {
            let addRouters = store.getters["permission/addRouters"];
            // 更新路由
            router.options.routes = store.getters["permission/allRouters"];
            // 添加动态路由
            router.addRoutes(addRouters);
            if (progressBar) NProgress.done();
            // es6 扩展运算符，防止内容发生变化的情况
            // replace: true 不被记录历史记录
            next({ ...to, replace: true });
          });
        }).catch(error => {
          // token 失效 返回登录
          next("/login");
        });
      } else {
        if (progressBar) NProgress.done();
        next();
      }
    }
    // 路由动态添加，分配菜单，每个角色不同的菜单
    // console.log('存在');
  } else {
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next("/login");
      if (progressBar) NProgress.done();
    }
  }
  // 设置标题
  if (to.meta.name) {
    document.title = getPageTitle(to.meta.name);
  }
});

router.afterEach(() => {
  if (progressBar) NProgress.done();
});
